#include "server.h"

using boost::asio::ip::tcp;

void tcp_connection::startRead()
{
    boost::asio::async_read(socket_,
        boost::asio::buffer(inBuffer,inBufferLenMax),
        boost::bind(&tcp_connection::receiveMsg, shared_from_this(),
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
}

void tcp_connection::receiveMsg ( const boost::system::error_code& error, 
                                  std::size_t bytes_transferred )
{
    server.receiveMsg ( inBuffer, bytes_transferred ) ;
        
    startRead() ;
}

void tcp_connection::writeMsg (std::string & writeMsg )
{
    boost::asio::async_write(socket_, boost::asio::buffer(writeMsg),
            boost::bind(&tcp_connection::handle_write, shared_from_this(),
                boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred));
}

void tcp_connection::handle_write(const boost::system::error_code& /*error*/,
        size_t /*bytes_transferred*/)
{
    std::cout<< "Server write" << std::endl ;
}


void tcp_server::start_accept()
{
    tcp_connection::pointer new_connection =
        tcp_connection::create(acceptor_.io_service(), *this);

    acceptor_.async_accept(new_connection->socket(),
            boost::bind(&tcp_server::handle_accept, this, new_connection,
                boost::asio::placeholders::error));
}

void tcp_server::handle_accept(tcp_connection::pointer new_connection,
        const boost::system::error_code& error)
{
    if (!error)
    {
        new_connection->startRead();
        start_accept();
    }
}

void tcp_server::receiveMsg ( char *pBuffer, size_t size )
{
    if (pRxMsg)
	{
        (*pRxMsg)(pObject, pBuffer, size) ;
    }
}